#!/usr/bin/perl -w
use strict;
use lib 'lib';
use lib 'lib/MT';
use lib 'extlib';
use MT;
use MT::Entry;
use MT::Category;
use Getopt::Long;

my ($EXPORT_PATH, $BLOG_ID, $USAGE);

my $MT_PATH = "";

$USAGE = <<USAGE
Usage:
mt-export-blog --blog <blog id number> --path <path_to_store>
USAGE
;

GetOptions("blog=i" => \$BLOG_ID, "path=s" => \$EXPORT_PATH );

sub get_categories
{
	my $entry = $_[0];

	my $categories_ = "";
	my $categories = $entry->categories;

	foreach my $category_object (@$categories)
	{
		my $category = MT::Category->load($category_object->id);
		$categories_ = $category->label . "," . $categories_;
	}

	$categories_ = substr($categories_, 0, -1);

	return $categories_;
}

sub get_status
{
	my $entry = $_[0];

	my $status = "";

	if($entry->status eq 2)
	{
		$status = "PUBLISH"; 
	}
	elsif($entry->status eq 1)
	{
		$status = "DRAFT";
	}
	
	return $status;
}

sub get_text
{
	my $entry = $_[0];
	
	my $text = $entry->text;

	if(defined($entry->text_more))
	{
		$text = $text . $entry->text_more;
	}

	return $text;
}

sub generate_filename
{
	my $entry = $_[0];

	my $permalink_individual = $entry->permalink("Individual");
	my @tokens = split('/', $permalink_individual);
	my $permalink = $tokens[6];
	$permalink = substr($permalink, 0, -5);
	$permalink = $permalink . ".mtb";
}

sub export_entry
{
	my $entry = $_[0];

	my $filename = &generate_filename($entry);

	my $id = $entry->id;
	my $status = &get_status($entry);
	my $author = $entry->author->name;

	my $permalink_category = $entry->permalink("Category");
	my $permalink_monthly = $entry->permalink("Monthly");
	my $permalink_individual = $entry->permalink("Individual");

	my $date = $entry->created_on;
	my $categories = &get_categories($entry);
	my $title = $entry->title;
	my $text = &get_text($entry);

	my $output = <<OUTPUT
$id
$status
$author
$permalink_category
$permalink_monthly
$permalink_individual
$date
$categories
$title
$text
OUTPUT
;
	my $file_out = '>>' . $EXPORT_PATH . $filename;
	print $file_out . "\n";
	open(OUTPUT_FILE, $file_out);
	print OUTPUT_FILE $output;
	close(OUTPUT_FILE); 
}


sub export_blog
{
	my $mt = $_[0];
	my $blog_id = $_[1];
	
	my $iter = MT::Entry->load_iter({ blog_id => $blog_id },{ 'sort' => 'created_on', direction => 'ascend' });
	
	while (my $entry = $iter->()) 
	{
		&export_entry($entry);
	}
}

sub main
{
	my $mt_config = $MT_PATH . 'mt.cfg';
	my $mt = MT->new( Config => $mt_config, Directory => $MT_PATH);
	
	if(defined($BLOG_ID) && defined($EXPORT_PATH))
	{
		&export_blog($mt, $BLOG_ID, $EXPORT_PATH);
	}
	else
	{
		print $USAGE;
	}
}

&main();
